package com.jcxy.filter;

import com.jcxy.pojo.Menu;
import com.jcxy.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 页面请求的拦截器，用于权限管理
 * 放行页面url：index.jsp,noPermission.jsp
 */
//@WebFilter(filterName = "PagePowerFilter",urlPatterns = "*.jsp")
public class PagePowerFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        //获取请求url，从中截取资源路径
        String requestURI = request.getRequestURI();
        String pagePowerUrl = requestURI.substring(requestURI.indexOf("/",1) + 1);//jsp页面路径（去除了jsp目录）

        String accessUrl = "index.jsp,noPermission.jsp";//可放行的页面url
        //请求的页面url不是可以放行的，需要判断是否有权限
        if(!accessUrl.contains(pagePowerUrl)){

            boolean isAccess = false;
            //获取登录的user对象
            User user = (User)request.getSession().getAttribute("user");
            //获取用户的菜单权限列表
            List<Menu> menuList = user.getRole().getMenuList();
            //遍历菜单权限列表
            for (Menu menu : menuList){

                //如果请求页面路径的权限存在，将标记置为true
                if (menu.getMenu_url().equals(pagePowerUrl)){
                    isAccess = true;
                    break;
                }
            }
            //遍历结束后判断是否有请求页面的权限
            if(!isAccess){
                //没有权限，跳转到noPermission.jsp页面
                response.sendRedirect("/jsp/noPermission.jsp");
            }
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
